using System;
using System.Collections;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using UnityEngine;
using LitJson;
using UnityEngine.Networking;
using Unity.VisualScripting;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Net;
using UnityEditor.ShaderGraph.Serialization;

namespace Game.NetWork
{
    public static class HttpWork
    {

        public delegate void JsonResult(string ret);


        /// <summary>
        ///  发送 Post 请求
        /// </summary>
        /// <param name="rootPath">网址</param>
        /// <param name="api">API</param>
        /// <param name="obj">序列化对象</param>
        /// <param name="result"></param>
        /// <returns></returns>
        public static IEnumerator PostMsg(string rootPath, String api, object obj, JsonResult result)
        {
            // 增加api
            string url = rootPath + "/" + api;
            // 准备请求数据
            string postData = JsonMapper.ToJson(obj);
            byte[] postDataBytes = Encoding.UTF8.GetBytes(postData);
            Debug.Log("Post请求 ：" + url + " post data : " + postData);

            // 创建 POST 请求
            UnityWebRequest request = new UnityWebRequest(url, "POST");
            request.uploadHandler = new UploadHandlerRaw(postDataBytes);
            request.downloadHandler = new DownloadHandlerBuffer();
            request.SetRequestHeader("Content-Type", "application/json");
            // 证书验证
            request.certificateHandler = new WebRequestCertificate();
            // 添加超时时间
            request.timeout = 10;
            // 发送请求
            yield return request.SendWebRequest();

            if (request.result == UnityWebRequest.Result.Success)
            {
                result.Invoke(request.downloadHandler.text);
                yield break;
            }
            else
            {
                // 打印错误信息
                Debug.Log("Http Post 请求发生错误 : " + request.error.ToString());
            }
            result.Invoke(string.Empty);
            yield break;
        }

        /// <summary>
        ///  发送 Get 请求
        /// </summary>
        /// <param name="rootPath">网址</param>
        /// <param name="api">API</param>
        /// <param name="myDictionary">键值对</param>
        /// <param name="result"></param>
        /// <returns></returns>
        public static IEnumerator GetMsg(string rootPath, String api, Dictionary<string, string> myDictionary, JsonResult result)
        {
            // 增加api
            string url = rootPath + "/" + api + "?";

            // 添加键值对
            foreach (KeyValuePair<string, string> pair in myDictionary)
            {
                // 遍历 Dictionary 中的所有键值对
                string kv = pair.Key + "=" + pair.Value + "&";
                Console.WriteLine(kv);
                url += kv;
            }
            Debug.Log("Get请求 ：" + url);

            // 获取 Get 属性的 request
            UnityWebRequest request = new UnityWebRequest(url, "GET");
            request.downloadHandler = new DownloadHandlerBuffer();
            // 证书验证
            request.certificateHandler = new WebRequestCertificate();
            // 添加超时时间
            request.timeout = 10;
            // 发送请求
            yield return request.SendWebRequest();

            if (request.isDone)
            {
                if (request.error != null)
                {
                    // 打印错误信息
                    Debug.Log("Http Get 请求发生错误 : " + request.error.ToString());
                }
                else
                {
                    result.Invoke(request.downloadHandler.text);
                    yield break;
                }
            }
            result.Invoke(string.Empty);
            yield break;
        }

        /// <summary>
        ///  将Json字符串反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="str"></param>
        /// <returns></returns>
        public static T? JsonToObject<T>(this string str) where T : class
        {
            JsonMapper.RegisterImporter<int, long>((int value) =>
            {
                return (long)value;
            });
            JsonMapper.RegisterImporter<long, int>((long value) =>
            {
                return (int)value;
            });
            JsonMapper.RegisterImporter<string, object>((string value) =>
            {
                return null;
            });

            // 解析 JSON 数据为对象
            T? obj = str == null ? null : JsonMapper.ToObject<T>(str);
            return obj;
        }

        /// <summary>
        ///  将Json字符串中选定的类反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="str"></param>
        /// <param name="index"></param>
        /// <returns></returns>
        public static T? JsonToObject<T>(this string str, string index) where T : class
        {
            // 找到对应的key
            JsonData jsonObject = JsonMapper.ToObject(str);
            //for (int i = 0; i < jsonObject.Count; i++)
            //{
            //    if (jsonObject[i] == null)
            //    {
            //        jsonObject[i] = "??";
            //    }
            //}

            string tmp = jsonObject[index]?.ToJson();
            Debug.Log($"Json index={index} 数据筛选 ： " + tmp);
            // 解析 JSON 数据为对象
            return tmp.JsonToObject<T>();
        }

        /// <summary>
        ///  将Json字符串中选定的类中特定的值反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="str"></param>
        /// <param name="index"></param>
        /// <param name="included"></param>
        /// <returns></returns>
        public static T? JsonToObject<T>(this string str, string index, params string[] included) where T : class
        {
            // 找到对应的key,并删除无用项
            JsonData jsonObject = JsonMapper.ToObject(str);
            JsonData jsonData = new JsonData();
            string includedTmp = "";

            if (jsonObject[index] != null)
            {
                foreach (var key in included)
                {
                    jsonData[key] = jsonObject?[index]?[key]??"??";
                    includedTmp += key + ", ";
                    //Debug.Log(key + " 值： " + jsonData[key] + " 类型： " + jsonData[key].GetJsonType());
                }
            }
            else
            {
                jsonData = null;
            }
            string tmp = jsonData?.ToJson();
            Debug.Log($"Json index={index} and included={includedTmp} 数据筛选 ： " + tmp);
            // 解析 JSON 数据为对象
            return tmp.JsonToObject<T>();
        }

    }

    /// <summary>
    ///  确认证书
    /// </summary>
    public class WebRequestCertificate : CertificateHandler
    {
        protected override bool ValidateCertificate(byte[] certificateData)
        {
            return true;
        }
    }
}
